package com.zhou.review3.controller;


import com.zhou.review3.entity.User;
import com.zhou.review3.serviceImpl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserServiceImpl userServiceImpl;

    @RequestMapping("list.do")
    public String list(Model model){
        List<User> users=userServiceImpl.findAllUsers();
        model.addAttribute("users",users);
        return "listUsers";
    }

    @RequestMapping("delete.do")
    public String delect(int id,Model model){
        userServiceImpl.removeUser(id);
        return list(model);
    }

    @RequestMapping("toAdd.do")
    public String toAdd(Model model){
        List<User> users=userServiceImpl.findAllUsers();
        model.addAttribute("users",users);
        return "addUser";
    }

    @RequestMapping("add.do")
    public String add(User user,Model model){
        userServiceImpl.addUser(user);
        return list(model);
    }

    @RequestMapping("toUpdate.do")
    public String toUpdate(int id,Model model){
        User user=userServiceImpl.findUser(id);
        model.addAttribute("user",user);
        return "updateUser";
    }
    //update,更新数据到数据库，回到listStudents.html
    @RequestMapping("update.do")
    public String update(User newUser,Model model){
        userServiceImpl.modifyUser(newUser);
        return list(model);
    }


    @RequestMapping("login.html")
    public String login(){
        return "login";
    }

    //Login.do
    @RequestMapping("login.do")
    public String login(String username, String password,HttpSession session,Model model){
        if(userServiceImpl.login(username,password))
        {
            session.setAttribute("username",username);
            return list(model);
        }
        else
            return "login";
    }
}
